package main

import (
	"database/sql"

	_ "github.com/go-sql-driver/mysql"
	"github.com/xelabs/go-mysqlstack/driver"
	"github.com/xelabs/go-mysqlstack/sqlparser/depends/query"
	"github.com/xelabs/go-mysqlstack/sqlparser/depends/sqltypes"
	"github.com/xuender/oils/base"
	"github.com/xuender/oils/logs"
)

func main() {
	client := base.Panic1(driver.NewConn("hexin", "hexin", "192.168.1.10:3306", "test", "utf8mb4"))
	defer client.Close()

	base.Panic1(client.Query("select * from test.books"))
}

// nolint
func Exec() {
	dsn := "hexin:hexin@tcp(192.168.1.10:3306)/test?charset=utf8mb4&parseTime=True"
	db := base.Panic1(sql.Open("mysql", dsn))
	res := base.Panic1(db.Exec("update test.books set name='ss' where id=1"))
	logs.Info(res.RowsAffected())

	if false {
		Select()
	}
}

func Select() {
	dsn := "hexin:hexin@tcp(192.168.1.10:3306)/test?charset=utf8mb4&parseTime=True"
	db := base.Panic1(sql.Open("mysql", dsn))
	rows := base.Panic1(db.Query("SHOW VARIABLES"))

	defer rows.Close()

	types := base.Panic1(rows.ColumnTypes())
	fields := make([]*query.Field, len(types))

	for index, fieldType := range types {
		field := &query.Field{Name: fieldType.Name()}

		if num, has := query.Type_value[fieldType.DatabaseTypeName()]; has {
			field.Type = query.Type(num)
		}

		fields[index] = field
	}

	resRow := [][]sqltypes.Value{}

	for rows.Next() {
		values := make([][]byte, len(fields))
		data := make([]any, len(fields))

		for i := range fields {
			data[i] = &values[i]
		}

		for i := 0; i < len(fields); i++ {
			data[i] = []byte{}
		}

		_ = rows.Scan(data...)

		row := make([]sqltypes.Value, len(fields))

		for i, field := range fields {
			row[i] = sqltypes.MakeTrusted(field.Type, values[i])
		}

		resRow = append(resRow, row)
	}

	res := &sqltypes.Result{
		Fields: fields,
		Rows:   resRow,
	}

	logs.Debug(res)
}
